package com.starblink.share.view

import android.app.Activity
import android.util.Log
import android.view.View
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.starblink.android.basic.ext.toastSuccess
import com.starblink.android.basic.ext.visibleOrGone
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.android.basic.util.ImageUtils
import com.starblink.android.basic.widget.dialog.BaseBottomSheetFragment
import com.starblink.basic.util.CommUtils
import com.starblink.rocketreserver.GenerateShortUrlQuery
import com.starblink.share.databinding.DialogShareLayoutBinding
import com.starblink.share.view.utils.ShareTypeEnum
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import java.io.File

class ShareDialog(
    val context: Activity,
    val originalUrl: String,
    val imageUrl: String? = "",
    val topicName: String? = "",
    val shareCome: ShareTypeEnum,
    val shareCall: () -> Unit
) :
    BaseBottomSheetFragment() {
    val channel_sms: String = "SMS"
    val channel_copy: String = "copylink"
    val channel_more: String = "more"
    val channel_whatsAppPersonal: String = "whatsapp_personal"
    val channel_whatsAppBusiness: String = "whatsapp_business_share"

    private val whatsapp: String = "whatsapp"
    private val facebook: String = "facebook"
    private val instagram: String = "instagram"

    lateinit var mBinding: DialogShareLayoutBinding
    override fun getBindingRootView(): View {
        mBinding = DialogShareLayoutBinding.inflate(layoutInflater)
        return mBinding.root
    }

    override fun initView() {
        mBinding.feedback.visibleOrGone(CommUtils.isFacebookEnable())
        mBinding.whatsapp.visibleOrGone(CommUtils.isWhatsAppEnable())
        mBinding.instagram.visibleOrGone(CommUtils.isInsAppEnable())
        mBinding.close.setOnClickListener {
            dismiss()
        }
        mBinding.feedback.setOnClickListener {
            getShortLink(facebook)
        }
        mBinding.whatsapp.setOnClickListener {
            getShortLink(whatsapp)
        }
        mBinding.instagram.setOnClickListener {
            getShortLink(instagram)
        }
        mBinding.message.setOnClickListener {
            getShortLink(channel_sms)
        }
        mBinding.copyLink.setOnClickListener {
            getShortLink(channel_copy)
        }
        mBinding.more.setOnClickListener {
            getShortLink(channel_more)
        }
    }

    private fun getOriginLink(channel: String): String {
        var rtn = originalUrl
        Log.e("ShareDialog", "====$rtn")
        var tail: String = if (rtn.contains("?")) {
            "&"
        } else {
            "?"
        }
        tail =
            "${tail}sfUid=${UserDataCenter.getAccountInfo()?.id}&sfPlatform=2&sfChannel=$channel&sfUniqueId=${
                UserDataCenter.getDeviceId(
                    context
                )
            }${System.currentTimeMillis()}"
//        rtn = "$rtn${tail.encodeBase64()}"
        rtn = "$rtn${tail}"
        return rtn
    }


    private fun getShortLink(channel: String) {
        CoroutineScope(Dispatchers.IO).launch {
            val response = SkGqlClient.skQuery(
                GenerateShortUrlQuery(
                    getOriginLink(channel)
                ),
                showDefaultLoading = true
            )
            if (response?.data != null && response.data!!.generateShortUrl != null && response.data!!.generateShortUrl.isNotEmpty()) {
                val url = response.data!!.generateShortUrl
                MainScope().launch {
                    when (channel) {
                        channel_sms -> {
                            CommUtils.sendMessage(context, composeShareMsg(url))
                        }
                        channel_copy -> {
                            CommUtils.copyText(url)
                            toastSuccess("Copied Successfully!")
                        }
                        channel_more -> {
                            CommUtils.sendMore(url)
                        }
                        whatsapp -> {
                            shareWithImg(imgShare = { resource ->
                                CommUtils.shareWhatsApp(
                                    resource,
                                    composeShareMsg(url),
                                    false
                                )
                            }, textShare = {
                                CommUtils.shareWhatsApp("", composeShareMsg(url), false)
                            })
                        }
                        facebook -> {
                            CommUtils.shareToFacebook(url, composeShareMsg(""))
                        }
                        instagram -> {
                            CommUtils.shareInstagramStory(context, "", "", composeShareMsg(url))
//                            shareWithImg(imgShare = { resource ->
//                                CommUtils.shareInstagramStory(
//                                    context,
//                                    resource,
//                                    "image",
//                                    url
//                                )
//                            }, textShare = {
//                                CommUtils.shareInstagramStory(context, "", "", url)
//                            })
                        }
                    }
                    shareCall.invoke()
                    dismiss()
                }
            }
        }
    }

    private fun shareWithImg(
        imgShare: (resource: String) -> Unit,
        textShare: () -> Unit
    ) {
        if (imageUrl.isNullOrEmpty()) {
            textShare.invoke()
        } else {
            ImageUtils.downloadImage(
                context,
                imageUrl,
                object : RequestListener<File> {
                    override fun onLoadFailed(
                        e: GlideException?,
                        model: Any?,
                        target: Target<File>?,
                        isFirstResource: Boolean
                    ): Boolean {
                        textShare.invoke()
                        return true
                    }

                    override fun onResourceReady(
                        resource: File?,
                        model: Any?,
                        target: Target<File>?,
                        dataSource: DataSource?,
                        isFirstResource: Boolean
                    ): Boolean {
                        if (resource != null
                        ) {
                            val filePath = ImageUtils.saveToAlbum(
                                context,
                                resource.absolutePath
                            )
                            if (filePath.isNotEmpty()) {
                                imgShare.invoke(filePath)
                            } else {
                                textShare.invoke()
                            }
                        } else {
                            textShare.invoke()
                        }
                        return true
                    }
                })
        }
    }


    private fun composeShareMsg(tail: String): String {
        var defaultMsgTxt: String
        when (shareCome) {
            ShareTypeEnum.PIC_POST, ShareTypeEnum.VIDEO_POST -> {
                defaultMsgTxt = "I've got something I want to share with you."
            }
            ShareTypeEnum.HASHTAG, ShareTypeEnum.TOPIC -> {
                defaultMsgTxt =
                    "Check out what's going on with $topicName in Guang!"
            }
            ShareTypeEnum.PERSONAL_HOME_SHARE -> {
                defaultMsgTxt =
                    "${UserDataCenter.getAccountInfo()?.username ?: UserDataCenter.getAccountInfo()?.userName} has just signed up for Guang! Snap a picture, identify the product and buy it instantly."
            }
            ShareTypeEnum.WISHLIST_BOARDS_SHARE -> {
                defaultMsgTxt =
                    "${UserDataCenter.getAccountInfo()?.username ?: ""} has added these amazing products to their Wishlist."
            }
            //        } else if (shareCome == ShareTypeEnum.shareType_s6 ||
            //            shareCome == ShareTypeEnum.shareType_s7 ||
            //            shareCome == ShareTypeEnum.shareType_s8 ||
            //            shareCome == ShareTypeEnum.shareType_s9
            //        ) {
            //            defaultMsgTxt =
            //                "${SkUserCenter().currUserName} has just signed up for Guang!
            //            Snap a picture, identify the product and buy it instantly.";
            else -> {
                defaultMsgTxt = ""
            }
        }
        var rtn = defaultMsgTxt
        if (tail.isNotEmpty()) {
            rtn = "$rtn\n$tail"
        }
        return rtn;
    }
}